<template>
  <div :class="[multipage === true ? 'multi-page':'single-page', 'not-menu-page', 'user-message']">
    <a-card :bordered="false">
      <div :class="advanced ? 'search' : null">
        <!-- 搜索区域 -->
        <a-form layout="horizontal">
          <a-row>
            <a-col :span="6" >
              <a-form-item>
                <a-range-picker @change="dateOnChange" v-model="queryParams.rangeData" />
              </a-form-item>
            </a-col>
            <a-col :span="1" >
            </a-col>
            <a-col :span="9" >
              <a-form-item>
                <a-radio-group default-value="0" @change="search" button-style="solid" v-model="queryParams.sourceType">
                  <a-radio-button value="0">
                    全部
                  </a-radio-button>
                  <a-radio-button value="1">
                    系统消息
                  </a-radio-button>
                  <a-radio-button value="2">
                    用户消息
                  </a-radio-button>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="8" align="right">
              <a-button type="primary" @click="search">查询</a-button>
              <a-button @click="reset">重置</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div>
        <div style="margin-bottom: 18px;">
          <a-button type="primary" ghost @click="add">新增</a-button>
          <a-button @click="batchDelete">删除</a-button>
        </div>
        <!-- 表格区域 -->
        <a-table ref="TableInfo"
                 :columns="columns"
                 :rowKey="record => record.id"
                 :dataSource="dataSource"
                 :pagination="pagination"
                 :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
                 :loading="loading"
                 :scroll="{ x: 1300 }"
                 @change="handleTableChange">
          <template slot="operation" slot-scope="text, record">
             <a @click="readMore(record)">阅读全文</a>
             <a @click="read(record)">已读</a>
          </template>
        </a-table>
        <userMessageAdd :userMessageAddVisible="userMessageAddVisible" @cancel="addClose" @success="addSuccess"></userMessageAdd>
        <userMessageFull ref="UserMessageFull" :visible="userMessageFullVisible" @cancel="readMoreClose"></userMessageFull>
      </div>
    </a-card>
  </div>
</template>

<script>
import {mapState} from 'vuex'
import UserMessageAdd from './UserMessageAdd'
import UserMessageFull from './UserMessageFull'

export default {
  name: 'UserManage',
  components: {UserMessageAdd, UserMessageFull},
  data () {
    return {
      // 数据初始区域
      userMessageAddVisible: false,
      userMessageFullVisible: false,
      advanced: false,
      queryParams: {},
      sortedInfo: null,
      paginationInfo: null,
      dataSource: [],
      selectedRowKeys: [],
      loading: false,
      pagination: {
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      }
    }
  },
  computed: {
    ...mapState({
      multipage: state => state.setting.multipage
    }),
    columns () {
      return [
        {
          title: '消息时间',
          width: 200,
          dataIndex: 'createTime'
        }, {
          title: '消息摘要',
          width: 600,
          ellipsis: true,
          dataIndex: 'message'
        }, {
          title: '来源',
          dataIndex: 'sourceType',
          customRender: (status) => {
            switch (status) {
              case '1':
                return <a-tag color="purple">系统消息</a-tag>
              case '2':
                return <a-tag color="blue">用户消息</a-tag>
              default:
                return status
            }
          }
        }, {
          title: '阅读状态',
          dataIndex: 'readFlg',
          customRender: (status) => {
            if (status) {
              return <a-tag color="green">已读</a-tag>
            } else {
              return <a-tag color="red">未读</a-tag>
            }
          }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          fixed: 'right',
          width: 150,
          scopedSlots: { customRender: 'operation' }
        }]
    }
  },
  mounted () {
    this.fetch()
  },
  methods: {
    dateOnChange (dates, dateStrings) {
      this.queryParams.range = dateStrings
      this.search()
    },
    read (record) {
      this.$get('admin/userMessage/read/' + record.id).then((res) => {
        if (res.data.status) {
          this.search()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    readMore (record) {
      this.$refs.UserMessageFull.setMessage(record.message)
      this.userMessageFullVisible = true
      this.read(record)
    },
    readMoreClose () {
      this.userMessageFullVisible = false
    },
    add () {
      this.userMessageAddVisible = true
    },
    addClose () {
      this.userMessageAddVisible = false
    },
    addSuccess () {
      this.userMessageAddVisible = false
      this.fetch()
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    batchDelete () {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择需要删除的记录')
        return
      }
      let that = this
      this.$confirm({
        title: '确定删除所选中的记录?',
        content: '当您点击确定按钮后，这些记录将会被彻底删除',
        centered: true,
        onOk () {
          let ids = []
          let selectedRowKeysStr = ',' + that.selectedRowKeys.join(',') + ','
          ids.push(that.dataSource.filter(f => { return selectedRowKeysStr.indexOf(',' + f.id + ',') > -1 }).map(m => { return m.id }))
          that.$delete('admin/userMessage/' + ids.join(',')).then((res) => {
            if (res.data.status) {
              that.$message.success(res.data.message)
              that.selectedRowKeys = []
              that.search()
            } else {
              that.$message.error(res.data.message)
            }
          })
        },
        onCancel () {
          that.selectedRowKeys = []
        }
      })
    },
    search () {
      let {sortedInfo, filteredInfo} = this
      let sortField, sortOrder
      // 获取当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field
        sortOrder = sortedInfo.order
      }
      this.fetch({
        sortField: sortField,
        sortOrder: sortOrder,
        ...filteredInfo
      }, this.queryParams)
    },
    reset () {
      // 重置分页
      this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
      if (this.paginationInfo) {
        this.paginationInfo.current = this.pagination.defaultCurrent
        this.paginationInfo.pageSize = this.pagination.defaultPageSize
      }
      // 重置列过滤器规则
      this.filteredInfo = null
      // 重置列排序规则
      this.sortedInfo = null
      // 重置查询参数
      this.queryParams = {}
      this.fetch()
    },
    handleTableChange (pagination, filters, sorter) {
      // 将这三个参数赋值给Vue data，用于后续使用
      this.paginationInfo = pagination
      this.filteredInfo = filters
      this.sortedInfo = sorter
      this.fetch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters
      }, this.queryParams)
    },
    fetch (params = {}, querypas) {
      // 显示loading
      this.loading = true
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
        params.pageSize = this.paginationInfo.pageSize
        params.pageNum = this.paginationInfo.current
      } else {
        // 如果分页信息为空，则设置为默认值
        params.pageSize = this.pagination.defaultPageSize
        params.pageNum = this.pagination.defaultCurrent
      }
      this.$get('admin/userMessage', {
        ...params, ...querypas
      }).then((r) => {
        let data = r.data
        const pagination = { ...this.pagination }
        pagination.total = data.total
        this.dataSource = data.rows
        this.pagination = pagination
        // 数据加载完毕，关闭loading
        this.loading = false
      })
    }
  }
}
</script>
<style lang="less">
  .user-message {
    .ant-card-body {
      padding: 1rem 0 !important;
      p {
        font-size: .9rem !important;
        margin-bottom: .6rem !important;
      }
    }
  }
</style>
